package info.javafans.cdn.dao;

import info.javafans.cdn.database.DbHelper;
import info.javafans.cdn.domain.News;

import java.sql.SQLException;
import java.util.List;
import org.apache.log4j.Logger;

/**
 * NewsDao Project: CollegeDatingNetwork <br />
 * ClassName: NewsDao <br />
 * Description: <br />
 */
public class NewsDao {

	public static Logger logger = Logger.getLogger(NewsDao.class);

	/**
	 * Get the latest news getLatestNews
	 * 
	 * @return
	 */
	public static List<News> getLatestNews() {
		String sql = "select * from news order by publishTime desc limit 0,5";

		// 从数据库中读取新闻列表
		List<News> newsList = null;
		
		newsList = DbHelper.queryBeanList(News.class, sql, null);
		
		// 为每个新闻对象添加作者
		for (News news : newsList) {
			news.setMember(MemberDao.selectMemberById(news.getMemberId()));
		}

		return newsList;
	}
	
	/**
	 * 发布新闻
	 * addNews
	 * @return
	 */
	public static boolean addNews(String topic, String content, int id) {
		String sql = "insert into news(topic, content, memberId) values(?,?,?)";
		
		int i = DbHelper.update(sql, topic, content, id);
		
		return i == -1 ? false: true;
	}
	
	/**
	 * 按id查询新闻
	 * selectNewsById
	 * @param id
	 * @return
	 */
	public static News selectNewsById(int id) {
		String sql = "select * from news where id = ?";
		News news = DbHelper.queryBean(News.class, sql, id);
		return news;
	}
	
	/**
	 * 查询所有新闻列表
	 * selectNewsList
	 * @return
	 */
	public static List<News> selectNewsList() {
		String sql = "select * from news";
		List<News> newsList = DbHelper.queryBeanList(News.class, sql, null);
		return newsList;
	}
	
	/**
	 * 查询头版新闻
	 * selectFrontNews
	 * @return
	 */
	public static News selectFrontNews() {
		String sql = "select * from news order by hits desc limit 0,1";
		News news = DbHelper.queryBean(News.class, sql, null);
		return news;
	}
}
